<?php
class Core_Model_Theme {
	
	protected $_option;
	
	protected $_area;

	public function __construct(Core_Model_Area $area, $option) {
		$this->_area = $area;
		$this->_option = $option;
	}

	public function getName() {
		return $this->_option['name'];
	}
	
	public function getTitle() {
		return isset($this->_option['title']) ? $this->_option['title'] : '';
	}
	
	public function getDescription() {
		return isset($this->_option['description']) ? $this->_option['description'] : '';
	}

	public function getParentTheme() {
		if (!isset($this->_option['parent'])) return null;
		return $this->_area->getTheme($this->_option['parent']);
	}

	public function getThumbnailUrl() {
		return isset($this->_option['thumbnail']) ?
			$this->getSkinUrl($this->_option['thumbnail']) :
			null;
	}

	public function setActive($active) {
		return $this->_area->activeTheme($this->getName());
	}

	protected function _getLayoutDir() {
		return $this->_getThemeDir() . DS . 'layout';
	}
	
	protected function _getTemplateDir() {
		return $this->_getThemeDir() . DS . 'template';
	}
	
	protected function _getSkinDir() {
		return $this->_getThemeDir() . DS . 'skin';
	}
	
	protected function _getThemeDir() {
		return $this->_area->getAreaDir() . DS . $this->getName();
	}

	public function getSkinUrl($file) {
		$fileName = $this->_getSkinDir() . DS . $file;
		$result = null;
		if (is_readable($fileName)) {
			$baseUrl = Mag::getUrl();
			$result = str_replace(DS, '/', str_replace(BP, $baseUrl, $fileName));
		} elseif ($this->getParentTheme()) {
			$result = $this->getParentTheme()->getLayoutFilename($file);
		}
		return $result;
	}
	
	public function getLayoutFilename($file) {
		$fileName = $this->_getLayoutDir() . DS . $file;
		$result = null;
		if (is_readable($fileName))
			$result = $fileName;
		elseif ($this->getParentTheme())
			$result = $this->getParentTheme()->getLayoutFilename($file);
		return $result;
	}

	public function getTemplateFilename($file) {
		$fileName = $this->_getTemplateDir() . DS . $file;
		$result = null;
		if (is_readable($fileName))
			$result = $fileName;
		elseif ($this->getParentTheme())
			$result = $this->getParentTheme()->getTemplateFilename($file);
		return $result;
	}
}